import React from 'react';
import ajax from 'superagent';

import Search from '../../components/search/Search';
import MainSortTab from '../../components/mainSortTab/MainSortTab';
import Sort from '../../components/sort/Sort';

class MainAthlete extends React.Component {
    constructor(props) {
        super(props);
        this.displayName = 'MainAthlete';
        this.url = '/api/players/';

        this.sort_mode_choices = {
            0: '-goals',  // default
            1: 'pingyin',
        }

        this.state = {
            sort_mode: this.sort_mode_choices[0],
            data: [],
        }
    }

    fetchingData( ordering ) {
        this.serverRequest = ajax.get(this.url)
            .query({'ordering': ordering})
            .end(function(error, response) {
                if( !error && response ) {

                    let data_origin = response.body;
                    let data = [];  // clean existed data

                    // 将返回的数据整理成需要的样子
                    data_origin.map(function( athlete, index ){
                        data.push({
                            id: athlete.id,
                            rank: athlete.ranking,
                            img: athlete.avatar_url,
                            name: athlete.name,
                            club: athlete.team,
                            score: athlete.goals,
                        });
                    });

                    this.setState({
                        data: data,
                        sort_mode: ordering,
                    });

                } else {
                    console.error(`Error fetching ${name} `, error);
             }
        }.bind(this) );

    }

    componentDidMount() {
        this.fetchingData(this.state.sort_mode);
    }

    componentWillUnmount() {
        this.serverRequest.abort();
    }

    changeSortMode(index) {
        this.fetchingData(this.sort_mode_choices[index]);
     }

    render() {

        let is_highlight_topn = (this.state.sort_mode.indexOf("goals") != -1);
        return (
            <div>
                <Search />
                <MainSortTab mode="athlete" changeTab = {this.changeSortMode.bind(this)}/>
                <Sort mode="athlete" sortColor ={is_highlight_topn} unit='个' data={this.state.data} />
            </div>
        );
    }
}

export default MainAthlete;
